/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pagoda.util.xml;

/**
 *
 * @author Kevin Krohe
 * Code originally written by priomsrb.  Posted to the following location:
 *
 * http://stackoverflow.com/questions/4915422/get-line-number-from-xml-node-java
 *
 *
 */
// PositionalXMLReader.java

import java.io.IOException;
import java.util.Stack;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import pagoda.util.StringUtil;
import pagoda.util.exceptions.PagodaException;

public class PositionalXMLReader {

    public final static String LINE_NUMBER_KEY_NAME = "__lineNumber__";
    public final static String FILENAME_KEY_NAME = "__fileName__";

    public static Document readXML(
            final InputSource is
            ) throws IOException, SAXException
    {
        return readXML(is, null);
    }

    public static Document readXML(
            final InputSource is,
            final String filname
            ) throws IOException, SAXException
    {
        final Document doc;
        SAXParser parser;
        try
        {
            final SAXParserFactory factory = SAXParserFactory.newInstance();
            parser = factory.newSAXParser();

            final DocumentBuilderFactory docBuilderFactory
                    = DocumentBuilderFactory.newInstance();

            final DocumentBuilder docBuilder
                    = docBuilderFactory.newDocumentBuilder();

            doc = docBuilder.newDocument();

        } catch (final Throwable t) {
            throw new PagodaException(
                    t,
                    "Failed to create SAX parser / DOM builder : %s",
                    t.getMessage()
                    );
        }

        final Stack<Element> elementStack = new Stack<Element>();
        final StringBuilder textBuffer = new StringBuilder();
        final DefaultHandler handler = new DefaultHandler()
        {
            private Locator locator;

            @Override
            public void setDocumentLocator(final Locator locator)
            {
                // Save the locator, so that it can be used later 
                // for line tracking when traversing nodes.
                this.locator = locator;
            }

            @Override
            public void startElement(
                    final String uri,
                    final String localName,
                    final String qName,
                    final Attributes attributes
                    ) throws SAXException
            {
                addTextIfNeeded();
                final Element el = doc.createElement(qName);
                for (int i = 0; i < attributes.getLength(); i++) {
                    el.setAttribute(
                            attributes.getQName(i),
                            attributes.getValue(i)
                            );
                }
                el.setUserData(
                        LINE_NUMBER_KEY_NAME,
                        String.valueOf(this.locator.getLineNumber()),
                        null
                        );
                if(!StringUtil.IsNullOrEmpty(filname))
                {
                    el.setUserData(
                            FILENAME_KEY_NAME,
                            String.valueOf(this.locator.getLineNumber()),
                            null
                            );
                    elementStack.push(el);
                }
            }

            @Override
            public void endElement(
                    final String uri,
                    final String localName,
                    final String qName
                    )
            {
                addTextIfNeeded();
                final Element closedEl = elementStack.pop();
                if (elementStack.isEmpty()) { // Is this the root element?
                    doc.appendChild(closedEl);
                } else {
                    final Element parentEl = elementStack.peek();
                    parentEl.appendChild(closedEl);
                }
            }

            @Override
            public void characters(
                    final char ch[],
                    final int start,
                    final int length
                    ) throws SAXException
            {
                textBuffer.append(ch, start, length);
            }

            // Outputs text accumulated under the current node
            private void addTextIfNeeded() {
                if (textBuffer.length() > 0) {
                    final Element el = elementStack.peek();
                    final Node textNode =
                            doc.createTextNode(textBuffer.toString());
                    el.appendChild(textNode);
                    textBuffer.delete(0, textBuffer.length());
                }
            }
        };
        parser.parse(is, handler);

        return doc;
    }
}
